// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "DBManager/Repository/HDF5/Input/Coordinate/CORDSummaryRepository.h"

#include "DBManager/Repository/HDF5/Base/HDF5RepositoryMacro.h"

HDF5_REG_REPOSITORY (CORDSummaryRepository)

using namespace SG::DBManager::HDF5;
using namespace SG::DBManager;
using namespace SG::DataStructure::FEM;

// ICoordinate
CORDSummaryRepository::CORDSummaryRepository (HDF5Database& database)
    : SingleRepositoryBase<SummaryInfo<SG::DataStructure::FEM::CoordTypes>> (database)
{}

void CORDSummaryRepository::InitialDatasetInfo ()
{
    RegisterTableInfo<SG::DataStructure::Common::Id> ("/OWN/INDEX/INPUT/COORDINATE_SYSTEM/COORDSUMMARY", IndexDataset);
    RegisterTableInfo<SummaryInfo<SG::DataStructure::FEM::CoordTypes>> ("/OWN/INPUT/COORDINATE_SYSTEM/COORDSUMMARY", MainDataset);
    CreateDatasetInFile ();
}

void CORDSummaryRepository::InitDataset ()
{
    SingleRepositoryBase<SummaryInfo<SG::DataStructure::FEM::CoordTypes>>::InitDataset ();

    auto insertData = [=] () {
        // 触发持久化信号
        GetDatabase ().GetHDF5Hub ()->m_coordinateSummarySignal ();

        // 便利所有index表，进行数据的读取
        for (auto&& i : GetDatabase ().GetHDF5Hub ()->m_coordinateTypeWithIndexPathMapping)
        {
            if (GetDatabase ().GetFile ()->exist (i.second))
            {
                std::vector<SG::DataStructure::Common::Id> idList;
                GetDataset (i.second).read (idList);

                std::vector<SummaryInfo<SG::DataStructure::FEM::CoordTypes>> info;

                info.reserve (idList.size ());
                for (size_t index = 0; index < idList.size (); index++)
                {
                    info.emplace_back (idList[index], i.first, index);
                }

                Add (info);
            }
        }
    };

    if (GetMainDatasetInfo ().GetRowCount () == 0)
    {
        insertData ();
        SortData ();
    }
}

SG::DataStructure::FEM::CoordTypes CORDSummaryRepository::GetCoordType (SG::DataStructure::Common::I64 id)
{
    SummaryInfo<SG::DataStructure::FEM::CoordTypes> info;  // NOLINT(misc-const-correctness)
    if (FindById (id, info) == SG::DataStructure::Common::Status::STATUS_Success)
    {
        return info.m_type;
    }

    return SG::DataStructure::FEM::CoordTypes::COORDTYPE_UnKonwn;
}
